import axios from 'axios'
import { encryption, decrypt } from '@/utils/crypto'

let isDevelopment = import.meta.env.MODE === 'development'
const service = axios.create()
// request interceptor
service.interceptors.request.use(
  (config) => {
    parameter(config) // 初始化参数
    confirmURL(config) // 确认URL地址
    encryption(config) // 加密请求数据
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    // 解密返回数据
    decrypt(response)
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

function parameter(config) {
  // 初始化参数
  config.params = config.params || {}
  config.data = config.data || {}
}

function confirmURL(config) {
  config.baseURL = isDevelopment ? '' : import.meta.env.VITE_BASE_API
}

export default service
